var Chat = require('./chat');
var chatwindow = require('./chatwindow');
var chatPeer = require('./chatPeer');
var imageViewer = require('./components/imageViewer');
var appEvent = require('./appEvent');
var EventTypes = require('./constants').EventTypes;
var chatInfo = require('./chatInfo');
var api = require('./api');
var RouteStrategy = require('./RouteStrategy');

imageViewer.init();
chatwindow.ready()
  .then(function (userId) {
    var store = chatInfo.target;
    var chatName = store.storeName;
    var chat = new Chat(chatInfo.chatId, chatName + '客服');
    var isNoticeSend = false;
    chat.ready(function () {
      chat.chatList.appendNotice('欢迎您的光临，我们将竭诚为您服务。');
      chat.active();

      // 如果指定了客服直接路由到该客服
      if (store.specialService) {
        chat.setFromSuid(store.specialService.id);
        chat.chatList.appendNotice('<span style="color:#ff211c">' + store.specialService.nickname + '</span> 已加入会话');
        isNoticeSend = true;
        chatPeer.active();
        return;
      }

      var ids = store.services.map(function (service) {
        return service.id;
      });

      api.getOnlineStatus(ids)
        .then(function (onlineList) {
          setTimeout(chatPeer.active, 0);
          var filter = RouteStrategy(store.strategyName);
          var service = filter(store, onlineList);

          console.info('当前服务', service);

          // 未知BUG，消息提醒可能发送多次,手动调整只发送一次
          if (isNoticeSend) return;

          if (!service) {
            chat.chatList.appendNotice('当前客服可能不在线，您可以联系平台客服。');
            return;
          }

          chat.setFromSuid(service.id);

          if (!service.online) {
            chat.chatList.appendNotice('当前客服可能不在线，您可以联系平台客服或者给客服留言，客服收到后会第一时间给你回复，谢谢。');
            return;
          }

          chat.chatList.appendNotice('<span style="color:#ff211c">' + service.nickname + '</span> 已加入会话');
          isNoticeSend = true;
        });
    });
  })
  .fail(function (err) {
    console.error('激活当前节点失败', err);
  });

$('body').on('set.send.key', function (event, key) {
  var $content = $('.ipt-content');
  $content.unbind('keydown');
  if (key == 'enter') {
    $('.ipt-content').on('keydown', function (event) {
      var $input = $(this);
      var chatId = $input.closest('.im-content').attr('id').substr('chat-'.length);
      var chat = Chat.getChat(chatId);
      var all = $input.contents();
      var ev = event || window.event;
      var keyCode = ev.keyCode ? ev.keyCode : ev.which;
      if (keyCode == 13 && !ev.ctrlKey) {
        ev.preventDefault();
        chat.sendMessage();
      } else if ((keyCode == 10 || keyCode == 13) && ev.ctrlKey) {
        console.log('$all', all);
        if (!all.length) {
          $input.append('<br><div><br></div>');
        } else {
          $input.append('<div><br></div>');
        }
        cursorToEnd($content);
      }
    });
  } else if (key == 'ctrlEnter') {
    $('.ipt-content').on('keydown', function (event) {
      var ev = event || window.event;
      var chatId = $(this).closest('.im-content').attr('id').substr('chat-'.length);
      var chat = Chat.getChat(chatId);
      if ((ev.keyCode == 10 || ev.keyCode == 13) && ev.ctrlKey) {
        chat.sendMessage();
      }
    });
  }
});

function cursorToEnd(obj) {
  if (window.getSelection) {//ie11 10 9 ff safari
    obj.focus(); //解决ff不获取焦点无法定位问题
    var range = window.getSelection();//创建range
    range.selectAllChildren(obj[0]);//range 选择obj下所有子内容
    range.collapseToEnd();//光标移至最后
  }
  else if (document.selection) {//ie10 9 8 7 6 5
    var range = document.selection.createRange();//创建选择对象
    //var range = document.body.createTextRange();
    range.moveToElementText(obj);//range定位到obj
    range.collapse(false);//光标移至最后
    range.select();
  }
}

// 当有新消息来时，闪烁标题
appEvent.addEventListener(EventTypes.RECEIVED_MESSAGE, function (message) {
  api.getUserInfo(message.from)
    .then(function (user) {
      var chat = Chat.getChat(user.storeId);
      if (chat && chat.fromSuid == user.id && !titleFlip) {
        console.log('消息开始闪烁...');
        onMessageTitleFlip();
        return;
      }
      console.log('消息不闪烁：\n消息为', message,'\n用户为', user, '\nchat为', chat, '\ntitleFlip', titleFlip);
    });
});

//标题闪烁
var titleCount = 0;
var titles = ['在线客服', '【有新的消息】_在线客服'];
var titleFlip;
function onMessageTitleFlip() {
  titleFlip = setInterval(function () {
    document.title = titles[titleCount % 2];
    titleCount++;
  }, 1000);
}


$(document).on('click', function () {
  console.log('消息停止闪烁...');
  clearInterval(titleFlip);
  titleFlip = null;
  document.title = titles[0];
});

// 发送按钮
$('.im-wrap')
  .on('click', '.im-send.send-btn', function () {
    var chatId = $(this).closest('.im-content').attr('id').substr('chat-'.length);
    var chat = Chat.getChat(chatId);
    chat.sendMessage();
  })
  // 关闭按钮
  .on('click', '.im-btn-area .close-btn', function () {
    var chatId = $(this).closest('.im-content').attr('id').substr('chat-'.length);
    var $tab = $('#tab-chat-' + chatId);
    if ($tab.prev('.im-title').length) {
      var previd = $tab.prev('.im-title').last().attr('id');
      var prevChatId = previd.substr(9);
      console.log('要激活的tab的groupId', prevChatId);
      Chat.getChat(prevChatId).active();
    } else if ($tab.next('.im-title').length) {
      var nextid = $tab.next('.im-title').first().attr('id');
      var nextChatId = nextid.substr(9);
      Chat.getChat(nextChatId).active();
    }
    if (!$tab.siblings('.im-title').length) {
      var leave = confirm('确定要结束当前会话吗？');
      if (leave) {
        document.write('窗口无法自动关闭，请自行关闭标签页');
        window.close();
      }
    } else {
      var chat = Chat.getChat(chatId);
      chat.close();
    }
  })
  .on('click', '.im-title', function () {
    var chatId = $(this).attr('id').substr('tab-chat-'.length);
    var chat = Chat.getChat(chatId);
    chat.active();
  })
  .on('click', '.im-clue-tab .tab-item', function () {
    $(this).find('.tab-content').removeClass('not-current').addClass('current');
    $(this).siblings().find('.tab-content').removeClass('current').addClass('not-current');
    var tabType = $(this).data('tab');
    var chatId = $('.im-title.spe').attr('id').substr('tab-chat-'.length);
    var chat = Chat.getChat(chatId);
    chat.content.clueInfo.clueContent.update(tabType, chatId);

  });

